package com.fingard.dsp.bank.directbank.gynsh01;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.gynsh01.util.JsonHelper;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import org.springframework.util.CollectionUtils;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description TODO
 * @Author xtt
 * @Date $ $
 **/
public class GYNSH01Transaction extends GYNSH01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        //历史明细查询返回ATS的对象
        RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAts.writeStart();//写返回ATS的统一头部信息
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                int startPatches = 1;
                boolean queryContinue = true;
                while (queryContinue) {
                    int countRd = 0;
                    JSONObject obj = new JSONObject();
                    SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
                //    obj.put("externalLocalDateText", yyyyMMdd.format(new Date()));// 当前日期	8	S	M	YYYYMMDD 北京时间
                    obj.put("tfAcNo", p_req7516.actNum);// 账号	32	S	M
                //    obj.put("tfAcSeqn", "0");// 账户序号	10	I	O
                    obj.put("startDate",Format.Date8Format.format(tmpCalendarFrom.getTime()));// 起始日期	8	S	M	YYYYMMDD
                    obj.put("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));// 终止日期	8	S	M	YYYYMMDD
                    obj.put("pageSize", "1000");// 每页笔数	5	I	O
                    obj.put("pageNumber", String.valueOf(startPatches));
                    JSONObject bizCont = JsonHelper.createBankBizCont(obj,getBankConfig().getValueAsString("privateKeyMerchant"),getBankConfig().getValueAsString("publicKeyBank"));
                    JSONObject headObj = createHead("gyns.details.acct.query");
                    headObj.put("biz_content", bizCont);
                    String retStrArr = sendToBank(headObj.toJSONString(), p_req7516.reqHeader.transType, p_req7516.reqHeader.commandCode);
                    if (retStrArr.length()>0) {
                        JSONObject json = JSONObject.parseObject(retStrArr);
                        if (Integer.valueOf(json.getString("totalRecordNumber"))>0) {
                            String respondCode = URLDecoder.decode(json.getString("accountTransactionDetails"),"UTF-8");
                            String respondInfo = json.getString("RspMsg");
                            if (respondCode != null) {
                                JSONArray ja = json.getJSONArray("accountTransactionDetails");
                                if(!CollectionUtils.isEmpty(ja)){

                                for(Object detail : ja){
                                        countRd++;
                                        tmpRespInfo = "success";
                                        RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                                        JSONObject detailInfo = JSONObject.parseObject(detail.toString());
                                        tmpRetDetail.actNum = URLDecoder.decode(detailInfo.getString("tfAcNo"),"UTF-8");
                                        String dealDate = detailInfo.getString("timeTxn");
                                        tmpRetDetail.tranDate = dealDate.substring(0, 4) + "-" + dealDate.substring(4, 6) + "-" + dealDate.substring(6, 8);
                                        tmpRetDetail.valueDate = tmpRetDetail.tranDate;
                                        tmpRetDetail.tranTime = detailInfo.getString("transactionTime");//格式"yyyy-MM-dd HH:mm:ss" transactionTime
                                        tmpRetDetail.usage = detailInfo.getString("strPostScript");
                                        tmpRetDetail.comment = detailInfo.getString("strPostScript");
                                        tmpRetDetail.abstr = pickupAbstr(detailInfo.getString("externalTransactionCode"));
                                        tmpRetDetail.recAccNum = detailInfo.getString("tfNo");
                                        tmpRetDetail.recAccName = detailInfo.getString("opponentAccountName");
                                        tmpRetDetail.recAccBank = detailInfo.getString("opponentBranchName");
                                        tmpRetDetail.accBal = detailInfo.getString("runningBalance");
                                        String cdflag = detailInfo.getString("drOrcrFlag");
                                        if ("C".equals(cdflag)) {
                                                tmpRetDetail.cdFlag = "2";
                                        }else if ("D".equals(cdflag)) {

                                                tmpRetDetail.cdFlag = "1";
                                        } else {
                                            tmpRespCode = "-1";
                                            tmpRespInfo = "借贷标志(" + cdflag + ")无法识别，请与银行核对";
                                            break;
                                        }
                                        tmpRetDetail.tranAmt =  detailInfo.getString("transactionAmount");
                                        tmpRetDetail.askNumber = detailInfo.getString("transactionReferenceNo");
                                        tmpRetDetail.bnkSeqNo = detailInfo.getString("refTxnNo");
                                        tmpRetDetail.originator = detailInfo.getString("transactionTeller");

                                    retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
                                if (countRd >= 20) {
                                    startPatches++;
                                } else {
                                    queryContinue = false;
                                }
                            } else {
                                //  "查询失败"
                                tmpRespCode = "0";
                                tmpRespInfo = respondInfo;
                                break;
                            }
                        } else {
                            //  "查询失败"
                            tmpRespCode = "0";
                            tmpRespInfo = json.getString("desc");
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = "请求失败";
                        break;
                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception e) {
            tmpRespCode = "-1";
            tmpRespInfo = e.getMessage();
            e.printStackTrace();
        }
        if (tmpRespCode.equals("-1")) {
            retAts = new RetAtsTrans(p_req7516.reqHeader);
            retAts.writeStart();//写返回ATS的统一头部信息
            retAts.writeRespCode(tmpRespCode);
            retAts.writeRespInfo(tmpRespInfo);
        } else if (retAts.getWrittenRdCount() == 0) {
            retAts.writeRespCode("0");
            retAts.writeRespInfo("交易为空");
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
        tmpReq7516.actArea = p_req7515.actArea;
        tmpReq7516.actCur = p_req7515.actCur;
        tmpReq7516.actNum = p_req7515.actNum;
        String tmpStrToday = Format.Date8Format.format(new Date());
        tmpReq7516.dateFrom = tmpStrToday;
        tmpReq7516.dateTo = tmpStrToday;
        return d_7516_HisTrans(tmpReq7516);
    }
}
